<template>
  <div>
    <el-container>
      <el-header style="padding: 0px;display:flex;justify-content:space-between;align-items: center">
        <div style="display: inline">
          <el-input
            placeholder="通过姓名搜索管理员,记得回车哦..."
            clearable
            style="width: 300px;margin: 0px;padding: 0px;"
            size="mini"
            prefix-icon="el-icon-search"
            v-model="queryData.name">
          </el-input>
          <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search" @click="searchUser">搜索</el-button>
          <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-plus" @click="showAddUserView">添加管理员</el-button>
        </div>
      </el-header>
      <el-main style="padding-left: 0px;padding-top: 0px">
        <div>
          <el-table
            :data="admins"
            v-loading="tableLoading"
            border
            stripe
            size="mini"
            >
            <el-table-column
              prop="workNo"
              label="工号">
            </el-table-column>
            <el-table-column
              prop="name"
              label="姓名">
            </el-table-column>
            <el-table-column
              prop="username"
              width="220"
              label="账号">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <el-button @click="showEditUserView(scope.row)" style="padding: 3px 4px 3px 4px;margin: 2px" size="mini">
                  编辑
                </el-button>
                <el-button type="danger" style="padding: 3px 4px 3px 4px;margin: 2px" size="mini"@click="deleteUser(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex;justify-content: space-between;margin: 2px">
            <el-pagination
              background
              :page-size="10"
              :current-page="currentPage"
              @current-change="currentChange"
              layout="prev, pager, next"
              :total="totalCount">
            </el-pagination>
          </div>
        </div>
        <el-dialog :title="title" :visible.sync="manageFormVisible">
          <el-form id="adminform" :model="admin" :rules="rules" ref="addUserForm">
            <el-form-item prop="workNo" label="工号" :label-width="formLabelWidth">
              <el-input v-if="!editFlag" v-model="admin.workNo" auto-complete="off"></el-input>
              <div v-if="editFlag" style="text-align: left"><span>{{admin.workNo}}</span></div>
            </el-form-item>
            <el-form-item prop="username" label="账号" :label-width="formLabelWidth">
              <el-input v-if="!editFlag" v-model="admin.username" auto-complete="off"></el-input>
              <div v-if="editFlag" style="text-align: left"><span>{{admin.username}}</span></div>
            </el-form-item>
            <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
              <el-input v-model="admin.name" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item v-if="!editFlag" prop="password" label="密码" :label-width="formLabelWidth">
              <el-input type="password" v-model="admin.password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item v-if="!editFlag" prop="confirmPwd" label="确认密码" :label-width="formLabelWidth">
              <el-input type="password" v-model="admin.confirmPwd" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item prop="roles" label="用户角色" :label-width="formLabelWidth">
              <el-select v-model="admin.selectedRoles" multiple placeholder="请选择角色" style="float:left">
                  <el-option
                    v-for="item in roles"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="saveAdmin">确 定</el-button>
            <el-button @click="hideEditUserView">取 消</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>
<script>
  export default {
    data() {
      let reg = /^\d{6}$/
      let validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (!reg.test(value)) {
          callback(new Error('密码格式为6位数字'));
        } else {
          if (this.admin.confirmPwd !== '') {
            this.$refs["addUserForm"].validateField('confirmPwd');
          }
          callback();
        }
      };
      let validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (!reg.test(value)) {
          callback(new Error('密码格式为6位数字'));
        } else if (value !== this.admin.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        keywords: '',
        queryData:{
          name:""
        },
        title: '添加管理员',
        manageFormVisible: false,
        totalFormVisible: false,
        admins: [],
        roles:[],
        admin: {
          workNo: '',
          username: '',
          name: '',
          password: '',
          confirmPwd: '',
          roles:[],
          selectedRoles:[]
        },
        total: {
          items: [],
          medicines: []
        },
        formLabelWidth: '120px',
        totalCount: -1,
        currentPage: 1,
        tableLoading: false,
        rules: {
          workNo: [{required: true, message: '必填:工号', trigger: 'blur'}, {pattern: /^\d{6}$/, message:'工号应为六位数字'}],
          name: [{required: true, message: '必填:姓名', trigger: 'blur'}],
          username: [{required: true, message: '必填:账号', trigger: 'blur'}],
          password: [
            { required: true, validator: validatePass, trigger: 'blur' }
          ],
          roles:[{required: true, message: '请选择角色', trigger: 'blur'}],
          confirmPwd: [
            { required: true, validator: validatePass2, trigger: 'blur' }
          ]
        },
        editFlag: false
      }
    },
    watch:{
      "admin.selectedRoles":function(val,oldValue){
        if(val && val.length >0){
          this.admin.roles = val.map(item =>{
          return {id:item}
        })
        }
      },
      "manageFormVisible":function(){
        this.emptyData();
      }
    },
    created () {
      this.getRequest('/system/basic/roles').then(res => {
        this.roles = res.data.map(item => {
          let result = {};
          result.value=item.id;
          result.label=item.nameZh
          return result;
        });
      })
    },
    mounted: function () {
      this.loadAdmin();
    },
    methods: {
      addItem: function () {
        this.total.items.push({
          name:'',
          price:0
        })
      },
      addMedicine: function () {
        this.total.medicines.push({
          name:'',
          price:0
        })
      },
      searchUser: function () {
        this.loadAdmin();
      },
      showAddUserView: function () {
        this.manageFormVisible = true;
        this.title = "添加管理员"
        this.editFlag = false
      },
      saveAdmin: function () {
        let _this = this;
         this.$refs["addUserForm"].validate((valid) => {
           if(valid){
             if (this.admin.id) {
              this.putJsonRequest("/userInfo/user/" + this.admin.id, this.admin).then(resp=> {
                _this.tableLoading = false;
                _this.hideEditUserView();
                _this.loadAdmin();
              }).catch(error =>{
                let message = error.message
                if (!!error.response && !!error.response.data) {
                  message = (error.response.data.message || message)
                }
                _this.$message({type: "error", message: message || '修改用户信息失败'});
              })
            } else {
              this.postJsonRequest("/userInfo/user", this.admin).then(resp=> {
                _this.tableLoading = false;
                _this.hideEditUserView();
                _this.loadAdmin();
              }).catch(error =>{
                let message = error.message
                if (!!error.response && !!error.response.data) {
                  message = (error.response.data.message || message)
                }
                _this.$message({type: "error", message: message || '新增用户失败'});
              })
            }
           }
         })
      },
      emptyData(){
        this.admin={
          workNo: '',
          username: '',
          name: '',
          password: '',
          confirmPwd: '',
          roles:[],
          selectedRoles:[]
        }
      },
      keywordsChange(val){
        if (val == '') {
          this.loadAdmin();
        }
      },
      loadAdmin: function () {
        var _this = this;
        this.tableLoading = true;
        //this.getRequest("/userInfo/user/list?pageNum=" + this.currentPage + "&pageSize=10&keywords=" + this.keywords ).then(resp=> {
        this.postJsonRequest("/userInfo/user/list?pageNum=" + this.currentPage + "&pageSize=10", this.queryData ).then(resp=> {
          this.tableLoading = false;
          if (resp && resp.status == 200) {
            if (resp.data) {
              let data = resp.data;
              _this.admins = data.result;
              _this.totalCount = data.total;
            } else {
              _this.admins = [];
              _this.totalCount = 0;
            }
//            _this.emptyMemberData();
          }
        }).catch((e) => {
          console.log(e)
        })
      },
      deleteUser(row) {
        this.$confirm('此操作将永久删除[' + row.name + '], 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.doDelete(row.id);
        }).catch(() => {
        });
      },
      doDelete(id) {
        let _this = this;
        this.deleteRequest("/userInfo/user/" + id).then(resp=> {
          _this.tableLoading = false;
          if (resp && resp.status == 200) {
            var data = resp.data;
            _this.$message({type: "success", message: "删除成功"});
            _this.loadAdmin();
          }
        })
      },
      showEditUserView(row) {
        if(row.id) {
          this.getRequest("/userInfo/user/"+row.id).then(res=> {
            let data = res.data;
            if(data.roles){
              data.selectedRoles = data.roles.map(item => item.id)
            }
            data.roles = []
            this.admin = data
          }).catch(error => {
            this.$message({type: "error", message: '获取用户信息失败'});
          })
        }
        this.title = "修改管理员"
        this.editFlag = true
        console.log(this.editFlag)
        this.manageFormVisible = true;
      },
      hideEditUserView () {
         this.manageFormVisible = false;
         this.emptyData()
      },
      currentChange(currentChange){
        this.currentPage = currentChange;
        this.loadAdmin();
      }
    }
  }
</script>
<style>
  .el-dialog__body {
    padding-top: 0px;
    padding-bottom: 0px;
  }

  .el-dialog__header {
    text-align: left;
  }
</style>
